package api

import (
	"context"
	"fmt"
	"github.com/gin-gonic/gin"
	ark "github.com/sashabaranov/go-openai"
	"net/http"
	"os"
	cfg "video_demo/config"
	"video_demo/service/video_service"
)

func VideoHandler(w http.ResponseWriter, r *http.Request) {

	if r.Method != http.MethodPost {
		http.Error(w, "Method not allowed", http.StatusMethodNotAllowed)
		return
	}

	videoPath := UploadVideo(w, r)
	if videoPath == "" {
		http.Error(w, "Failed to upload video", http.StatusInternalServerError)
		return
	}

	text := AudioToText(videoPath)
	if text == "" {
		http.Error(w, "Failed to convert audio to text", http.StatusInternalServerError)
		return
	}

	reasoning := AudioReasoning(text)
	if reasoning == "" {
		http.Error(w, "Failed to generate reasoning", http.StatusInternalServerError)
		return
	}

	w.Header().Set("Content-Type", "text/plain")
	w.WriteHeader(http.StatusOK)
	w.Write([]byte(reasoning))
}

func Video(c *gin.Context) {
	videoPath := UploadVideo(c.Writer, c.Request)
	if videoPath == "" {
		http.Error(c.Writer, "Failed to upload video", http.StatusInternalServerError)
		return
	}

	text := AudioToText(videoPath)
	if text == "" {
		http.Error(c.Writer, "Failed to convert audio to text", http.StatusInternalServerError)
		return
	}

	reasoning := AudioReasoning(text)
	if reasoning == "" {
		http.Error(c.Writer, "Failed to generate reasoning", http.StatusInternalServerError)
		return
	}

	c.Writer.Header().Set("Content-Type", "text/plain")
	c.Writer.WriteHeader(http.StatusOK)
	c.Writer.Write([]byte(reasoning))
}
func UploadVideo(w http.ResponseWriter, r *http.Request) string {
	// 解析上传文件
	file, header, err := r.FormFile("video")
	if err != nil {
		http.Error(w, "Invalid file upload", http.StatusBadRequest)
		return ""
	}
	defer file.Close()

	// 调用转换函数
	outputPath, err := video_service.Mp4ToMp3(header)
	if err != nil {
		http.Error(w, err.Error(), http.StatusInternalServerError)
		return ""
	}

	// 返回结果
	fmt.Println(w, "MP3 generated at: %s", outputPath)
	return outputPath
}

func AudioToText(audioPath string) string {
	appid := "8364911036"
	token := "zv5Z_YTIEyC8YNsXT9r-NGSETeknwWNQ"
	cluster := "volcengine_streaming_common"
	audioFormat := "mp3" // wav 或 mp3，根据音频格式设置

	client := video_service.BuildAsrClient()
	client.Appid = appid
	client.Token = token
	client.Cluster = cluster
	client.Format = audioFormat

	audioData, err := os.ReadFile(audioPath)
	if err != nil {
		fmt.Println("fail to read audio file", err.Error())
		return ""
	}
	asrResponse, err := client.RequestAsr(audioData)
	if err != nil {
		fmt.Println("fail to request asr, ", err.Error())
		return ""
	}
	return asrResponse.Results[0].Text
}

func AudioReasoning(text string) string {
	config := ark.DefaultConfig(os.Getenv("ARK_API_KEY"))
	config.BaseURL = cfg.SysConfig.AIModel.URL
	client := ark.NewClientWithConfig(config)

	fmt.Println("----- standard request -----")
	resp, err := client.CreateChatCompletion(
		context.Background(),
		ark.ChatCompletionRequest{
			Model: cfg.SysConfig.AIModel.VersionModel,
			Messages: []ark.ChatCompletionMessage{
				{
					Role: ark.ChatMessageRoleSystem,
					Content: "你现在的角色是一名教师助理，请根据老师的课堂讲义进行知识点总结归纳，可以稍微详细一点。" +
						"并标记出关键知识点的位置，例如：02:23:31,注意时间的准确性，不要超过原有的时间",
				},
				{
					Role:    ark.ChatMessageRoleUser,
					Content: text,
				},
			},
		},
	)
	if err != nil {
		fmt.Printf("ChatCompletion error: %v\n", err)
		return ""
	}
	result := resp.Choices[0].Message.Content
	fmt.Println(result)
	return result
}
